package com.xt.base.wireless.server.socket;

import java.io.IOException;
import java.net.ServerSocket;

import org.apache.log4j.Logger;

import com.xt.base.util.SpringUtil;

/**
 *  <br>
 * <br>
 * 
 * <p>
 * <a href="SocketServerListener.java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 杨洪波
 * @create-date:2010-9-12
 */
public class SocketServerListener implements Runnable{
	Logger log = Logger.getLogger(SocketServerListener.class);
	private ServerSocket serverSocket=null;
	private boolean listening=true;
	private long clientNum = 0;
	private int port = 13826;
	
	public SocketServerListener(int port){
		this.port = port;
		SocketConnectionPool mcp = SpringUtil.getWebBean("socketConnectionPool");
		if(port==0){
			this.port = mcp.getPort();
		}
		this.start();
	}
	
	public SocketServerListener(){
		SocketConnectionPool mcp = SpringUtil.getWebBean("socketConnectionPool");
		this.port = mcp.getPort();
		this.start();
	}
	
	public void start(){
		Thread th = new Thread(this);
		th.start();
	}
	
	public void run() {
		log.info("PC端MOA服务Socket监听器已启动...，端口："+port);
		try{
			//创建一个ServerSocket在端口5000监听客户请求
			serverSocket=new ServerSocket(port);
			while(listening){ //永远循环监听
				//监听到客户请求，根据得到的Socket对象和
				new SocketServerThread(serverSocket.accept(),clientNum).start();
				if(clientNum>=100000){
					log.info("Socket链接计数器已达到"+clientNum+",需要归零，重新计数！");
					clientNum = 0;
				}
				//客户计数创建服务线程，并启动之
				clientNum++; //增加客户计数
			}
			
		}catch(IOException e) {
			e.printStackTrace();
		}finally{
			try{
			if(serverSocket!=null)serverSocket.close(); //关闭ServerSocket
			}catch(Exception e){
				log.info("关闭PC端MOA服务器端的socket时出错！",e);
			}
		}
		log.info("PC端MOA服务器端已关闭...");
	}
	
	public static void main(String[] args){
		new SocketServerListener().run();
	}

	public void setPort(int port) {
		this.port = port;
	}

}
